package com.shiro.demo;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *  HelloWorld，体验Shiro的工作流程
 * @author hjwStart
 * @time 2022-11-21 10:47
 * @version: 1.0
 */
public class Demo1 {

    private static final Logger logger = LoggerFactory.getLogger(Demo1.class);
    public static void main(String[] args) {
        // 1. 设置Realm（读取ini配置文件）
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        // 2. 创建SecurityManager实例
        SecurityManager securityManager = factory.getInstance();
        // 3. 将SecurityManager对象存放到Shiro的全局安全管理对象中
        SecurityUtils.setSecurityManager(securityManager);
        // 4.通过 Shiro的全局安全管理对象获取当前程序的主体
        Subject currentUser = SecurityUtils.getSubject();
        // 5.获取当前用户的认证状态
        boolean authenticated = currentUser.isAuthenticated();
        logger.info("当前用户是否认证：{}",authenticated ? "已认证" : "未认证");
        if (!authenticated){
            logger.info("开始认证");
            // 使用 UsernamePasswordToken 封装Subject的Principals和Credentials信息
            UsernamePasswordToken token = new UsernamePasswordToken("admin", "123123");
            try {
                // 执行认证操作
                currentUser.login(token);
                logger.info("认证成功");
            } catch (Exception e) {
                // 可以在这里自定义异常
                logger.error("认证失败");
            }
        }
    }
}
